import React, { memo, useEffect, useRef, useState } from 'react';
import {
  RefreshControl,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  NativeSyntheticEvent,
  NativeScrollEvent,
  useColorScheme,
} from 'react-native';
import WaterFallList from '../Components/WaterFallList';
import Item from '../Components/NoteCard.tsx';
import { IWaterFallList } from '../Components/type';
import SearchBar from '../Components/SearchBar.tsx';
import Icon from 'react-native-vector-icons/FontAwesome';

// 生成随机 ID
const generateRandomId = () => {
  return Math.floor(Math.random() * 1000000).toString();
};

// 定义 ListItem 类型
export interface ListItem { // 添加 export
  author: string;
  id: string;
  imageUrl: string;
  subtitle: string;
  title: string;
  views: number;
  height: number;
}

// 定义 fetchData 的返回值类型
const fetchData = async (): Promise<ListItem | null> => {
  const id = generateRandomId();
  const url = `http://10.128.128.188:4523/m1/6361734-6057711-default/api/note/cover/${id}`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('网络响应失败');
    }
    const data: ListItem = await response.json();
    data.id = id;
    data.imageUrl='https://picsum.photos/800/1200?random=' + id;
    return data;
  } catch (error) {
    console.error('获取数据时出错:', error);
    return null;
  }
};

const App = ({navigation}:{navigation:any}) => {
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  const [list, changeList] = useState<ListItem[]>([]);
  const waterfallRef = useRef<IWaterFallList>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showScrollToTop, setShowScrollToTop] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // 修改 fetchBatchData 的返回值类型
  const fetchBatchData = async (count: number): Promise<ListItem[]> => {
    const promises = Array.from({ length: count }, fetchData);
    const results = await Promise.all(promises);
    return results.filter((data): data is ListItem => data !== null);
  };

  // 提取重复逻辑到一个函数中
  const updateList = async (count: number, isRefresh: boolean) => {
    if (isLoading && !isRefresh) {return;}
    if (isRefresh) {
      setIsRefreshing(true);
    } else {
      setIsLoading(true);
    }
    try {
      const newData = await fetchBatchData(count);
      if (newData.length > 0) {
        if (isRefresh) {
          waterfallRef.current?.refreshList();
          changeList(newData);
        } else {
          const uniqueList = [...list, ...newData].filter(
            (item, index, self) =>
              self.findIndex(i => i.id === item.id) === index,
          );
          changeList(uniqueList);
        }
      }
    } finally {
      if (isRefresh) {
        setIsRefreshing(false);
      } else {
        setIsLoading(false);
      }
    }
  };

  const refresh = async () => {
    await updateList(10, true);
  };

  const onEndReached = async () => {
    await updateList(10, false);
  };

  const scrollToTop = () => {
    waterfallRef.current?.refreshList(0);
    setShowScrollToTop(false);
  }

  // 修改 handleScroll 的事件类型
  const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const offsetY = event.nativeEvent.contentOffset.y;
    setShowScrollToTop(offsetY > 500); // 滚动超过 500 显示按钮
  };

  useEffect(() => {
    const loadInitialData = async () => {
      await updateList(10, true);
    };
    loadInitialData();
  }, []);

  return (
    <View
      style={{
        height: '100%',
        width: '100%',
        backgroundColor: isDarkMode ? '#121212' : '#999',
      }}>
      <View
        style={{
          width: '100%',
          backgroundColor: isDarkMode ? '#1E1E1E' : 'white',
          height: 100,
          marginBottom: 10,
        }}>
        <SearchBar navigation={navigation}/>
      </View>
      <WaterFallList
        ref={waterfallRef}
        ItemSeparatorComponent={() => {
          return <View style={{width: '100%', height: 10}} />;
        }}
        initialNumToRender={10}
        windowSize={10}
        ListHeaderComponent={() => null}
        renderItem={({item}) => <Item data={item} navigation={navigation}/>}
        data={list}
        contentContainerStyle={{flexGrow: 1}}
        onEndReachedThreshold={0.5}
        onEndReached={onEndReached}
        numColumns={2}
        showsVerticalScrollIndicator={false}
        onScroll={handleScroll}
        scrollEventThrottle={16}//节流 每16ms只能触发一次，60fps
        ListEmptyComponent={() => {
          return (
            <View
              style={{
                width: '100%',
                height: '100%',
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: isDarkMode ? '#1E1E1E' : 'pink',
              }}>
              <Text style={{fontSize: 30, color: isDarkMode ? '#FFFFFF' : 'red'}}>网络错误，加载失败</Text>
            </View>
          );
        }}
        ListFooterComponent={() => null}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={refresh}
            colors={['#0000FF']} // 自定义刷新指示器颜色
            tintColor="#0000FF" // 自定义指示器颜色
          />
        }
      />
      {showScrollToTop && ( // 根据状态显示按钮
        <TouchableOpacity
          style={styles.scrollToTopButton}
          onPress={scrollToTop}>
            <Icon name="angle-double-up" size={28} color="#fff" />
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  scrollToTopButton: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    backgroundColor: 'black',
    borderRadius: 25,
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
export default memo<typeof App>(App);
